package cn.tedu.charging.device.dao.repository;

import cn.tedu.charging.common.pojo.po.ChargingGunInfoPO;
import cn.tedu.charging.device.dao.mapper.ChargingGunInfoMapper;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Slf4j
public class GunRepository {
    @Autowired
    private ChargingGunInfoMapper chargingGunInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public List<ChargingGunInfoPO> getGunsByStationId(Integer stationId) {
        //1.读取缓存
        String stationGunsKey="station:guns:cache:"+stationId;
        ListOperations<String,ChargingGunInfoPO> listOps = redisTemplate.opsForList();
        //list 结构 写数据lpush rpush 读数据 lrange key 0 -1
        List<ChargingGunInfoPO> gunPos = listOps.range(stationGunsKey, 0, -1);
        //2.判断缓存命中命中则直接返回
        if (CollectionUtils.isNotEmpty(gunPos)){
            log.debug("缓存命中,查询到guns:{}",gunPos);
            return gunPos;
        }else{
            //3.没命中读取数据库
            log.debug("缓存未命中,查询数据库");
            gunPos= chargingGunInfoMapper.selectGunsByStationId(stationId);
            if (CollectionUtils.isNotEmpty(gunPos)){
                //4.存放一次缓存 非空的时候 才存放缓存
                listOps.leftPushAll(stationGunsKey,gunPos);
            }
            //5.返回数据库读取的数据
            return gunPos;
        }
    }

    public Integer countByIdAndStatus(Integer gunId, Integer status) {
        //查询一下 是否存在 枪 枪是否空闲 select count(1) from charging_gun_info where id=#{gunId}
        //and status=1
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("id",gunId);
        queryWrapper.eq("gun_status",status);
        return chargingGunInfoMapper.selectCount(queryWrapper).intValue();
    }
}
